package ph.com.gs3.formalistics.view.document.abstractfields;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.formalistics.global.constants.Constants;
import android.content.Context;
import android.widget.LinearLayout;
import android.widget.TextView;

public abstract class AbstractFieldView extends LinearLayout {

	public static final String TAG = AbstractFieldView.class.getSimpleName();
	public static final String PROMPT_FIELD_REQUIRED = "This field is required";
	
	public static final int GROUP_VIEWS_RIGHT_PADDING = 19;
	public static final String MULTI_VALUE_SEPARATOR_ESCAPED = "\\|\\^\\|";
	public static final String MULTI_VALUE_SEPARATOR = "|^|";

	private boolean changeListenerInitialized = false;

	protected List<AbstractFieldChangeListener> changeListeners;

	protected String fieldId;
	protected boolean isEnabled;

	protected static final LayoutParams lpFillWidth = new LayoutParams(
	        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

	public AbstractFieldView(Context context, String fieldId) {
		super(context);
		this.fieldId = fieldId;

		changeListeners = new ArrayList<>();
	}

	protected void createLabeledDefaultContainer(String label, String tag) {

		createDefaultContainer(tag);

		TextView tvLabel = new TextView(getContext());
		tvLabel.setText(label);
		tvLabel.setTypeface(Constants.getApplicationInstance().getGlobalTypeface());

		this.addView(tvLabel);

	}

	protected void createDefaultContainer(String tag) {

		this.setTag(tag);
		this.setLayoutParams(lpFillWidth);
		this.setOrientation(LinearLayout.VERTICAL);
	}

	public String getFieldId() {
		return fieldId;
	}

	public boolean isEnabled() {
		return isEnabled;
	}

	public void setEnabled(boolean isEnabled) {
		this.isEnabled = isEnabled;
	}

	public void addOnChangeListener(AbstractFieldChangeListener abstractFieldChangeListener) {
		changeListeners.add(abstractFieldChangeListener);

		if (!changeListenerInitialized) {
			initializeChangeListener();
			changeListenerInitialized = true;
		}
	}

	public void notifyValueChanged() {
		for (AbstractFieldChangeListener changeListener : changeListeners) {
			changeListener.onChange(getValue());
		}
	}

	protected abstract void initializeChangeListener();

	public abstract String getValue();

	public abstract void setValue(String value);

	public abstract void showError(String errorMessage);
	
	public static interface AbstractFieldChangeListener {
		public void onChange(String newValue);
	}

}
